package com.example.tool.web.dd;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.tool.bean.LogisticsEntitiesDO;
import com.example.tool.bean.ddaiexcel.AddAiSheetRecordAttachmentDTO;
import com.example.tool.bean.ddaiexcel.AddAiSheetRecordsRequest;
import com.example.tool.bean.ddaiexcel.AddAiSheetRecordsResponse;
import com.example.tool.conf.ScheduledTasks;
import com.example.tool.erp.sdk.api.sales.dto.TradeQueryResponse;
import com.example.tool.util.DDUtil;
import com.example.tool.util.WDTUtil;
import com.example.tool.util.WeChatUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

import static com.example.tool.util.ExportUtil.writeExcel;

@RestController
//@CrossOrigin(origins = "*")
@RequestMapping("/tool/dd")
@Slf4j
public class DDController {
    @Autowired
    private WeChatUtil weChatUtil;

    @PostMapping("/readData")
    public void readData(@RequestParam("file") MultipartFile file, HttpServletResponse response) {
        try {

            LogisticsEntitiesDO lastItem = new LogisticsEntitiesDO();
            Calendar calendar = Calendar.getInstance();
            calendar.add(Calendar.DATE, -1);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
            String nowStr = sdf.format(calendar.getTime());
            List<LogisticsEntitiesDO> dataList = EasyExcel.read(file.getInputStream())
                    .sheet()
                    .head(LogisticsEntitiesDO.class)
                    .doReadSync();
            dataList = dataList.stream()
                    .filter(e -> StringUtils.isNotBlank(e.getExpressDeliveryAndNo()))
                    .peek(e -> {
                        e.setExpressDeliveryAndNo(
                                e.getExpressDeliveryAndNo().replaceAll("[\\u4e00-\\u9fa5\\p{P}\\p{S}\\s]", "")
                        );
                        e.setDateStr(nowStr);
                        TradeQueryResponse.OrderItem orderItem = WDTUtil.logisticsNoQueryOrder(e.getExpressDeliveryAndNo());
                        if (ObjectUtil.isNotNull(orderItem)) {
                            e.setShopName(orderItem.getShopName());
                            e.setCircumstance(orderItem.getCsRemark());
                        }
                    }).collect(Collectors.toList());
            List<LogisticsEntitiesDO> finalDataList = dataList;
            int lastIndex = IntStream.range(0, dataList.size())
                    .boxed()  // 转为Stream<Integer>以便使用Comparator
                    .sorted(Collections.reverseOrder())  // 逆序排序
                    .filter(i -> {
                        String str = finalDataList.get(i).getExpressDeliveryAndNo();
                        return str != null && str.length() <= 8;
                    })
                    .findFirst()
                    .orElse(-1);

            dataList = dataList.subList(lastIndex + 1, dataList.size());
            lastItem.setExpressDeliveryAndNo(nowStr);
            dataList.add(lastItem);

            writeExcel(response, dataList, "result.xlsx", "表名", LogisticsEntitiesDO.class);
        } catch (Exception e) {
            e.printStackTrace();

        }
    }
//    @Autowired
//    private ScheduledTasks scheduledTasks;
//    @Autowired
//    private PDDTasks pddTasks;
//      @Autowired
//      private SelfOrderService selfOrderService;
//    @Autowired
//    private PDDSendGoodsTasks pDDSendGoodsTasks;

    @PostMapping("/test2")
    public void test2(HttpServletResponse response, @RequestBody JSONObject jsonObject) {
        System.out.println(jsonObject);
    }
//    @Autowired
//    private OrderLogisticsAbnormalityCollectTasks orderLogisticsAbnormalityCollectTasks;
//    @Autowired
//    private SelfOrderCollectTasks selfOrderCollectTasks;
//    @Autowired
//    private ScheduledTasks scheduledTasks;
//      @Autowired
//      private SelfOrderService selfOrderService;
//@Autowired
//private RedisService redisService;
    /// / @Autowired
    /// /private PDDTasks pddTasks;
// @Autowired
//private SelfOrderMonitorCollectTasks pddTasks;
// @Autowired
//private SelfOrderService selfOrderService;
// @Autowired
//private InventoryShortageTasks inventoryShortageTasks;
    @Autowired
    private ScheduledTasks scheduledTasks;

    // @Autowired
//private ClaimsInfoService claimsInfoService;
    //dc4Unf5fs8kfKdDTSudFvIci1lVv0v6j9ROqHeZR-2Gg90WDF5GAKIrsTLt-3XOqn6u6HRHyCZTGsPyXuPzO-wnQ
    @PostMapping("/test")
    @Async
    public void test(HttpServletResponse response2, @RequestBody JSONObject r) throws Exception {
//        System.out.println(DDUtil.getToken());
        scheduledTasks.scheduledImportClaims();
//        WeChatUtil.deleteSmartSheetFields("dcd4cd02TGwQkmrnqwv55b10aE1R-TRL7ngqpHfySuD3WfStbOqxX97Kl6h1MEQHmLJrspW9B6BKDTsPS1_iopWw",
//                "04Ynpn",Arrays.asList("fabcde") );
//   WeChatUtil.deleteSmartSheetFields("dcuWuxBLC99L8Fd1i7rvlX6LOdZ7UD33VHTTFjZf8I9O9lJFk2ZCzsWtoCpfQYc6boqpDrQ5VcM_2qkzBTgNWquw","",Arrays.asList("fGlUOn"));
//        RobotMessage textMessage = RobotMessage.initMessage("订单未发仓内拦截通知-测试阶段\n" +
//                "原始单号：250705-275618229942049\n" +
//                "出库单号：CK2025070531132\n" +
//                "订单编号：JY2025070522732\n" +
//                "物流单号：\n" +
//                "创建时间：2025-07-05 16:31:49\n" +
//                "发货时间：\n" +
//                "揽收时间：\n" +
//                "\n" +
//                "原始单号：250705-540897482500486\n" +
//                "出库单号：CK2025070531128\n" +
//                "订单编号：JY2025070522721\n" +
//                "物流单号：\n" +
//                "创建时间：2025-07-05 16:31:29\n" +
//                "发货时间：\n" +
//                "揽收时间：\n" +
//                "\n" +
//                "原始单号：6944082769537341277\n" +

//                "出库单号：CK2025070531216\n" +
//                "订单编号：JY2025070522975\n" +
//                "物流单号：\n" +
//                "创建时间：2025-07-05 16:37:36\n" +
//                "发货时间：\n" +
//                "揽收时间：\n" +
//                "\n" +
//                "原始单号：250705-419168284291402\n" +
//                "出库单号：CK2025070531143\n" +
//                "订单编号：JY2025070522766\n" +
//                "物流单号：\n" +
//                "创建时间：2025-07-05 16:32:36\n" +
//                "发货时间：\n" +
//                "揽收时间：\n" +
//                "\n" +
//                "原始单号：P767256011556034791\n" +
//                "出库单号：CK2025070531610\n" +
//                "订单编号：JY2025070522513\n" +
//                "物流单号：\n" +
//                "创建时间：2025-07-05 16:26:58\n" +
//                "发货时间：\n" +
//                "揽收时间：\n" +
//                "\n" +
//                "处理类型：订单未发运，终止出库，退换单请及时入库。\n" +
//                "https://doc.weixin.qq.com/sheet/e3_AAcAoBTlAIACNVmhA70D9TCC5jeAW_a?scode=AE8AywdOADswF2Ye1cAAcAoBTlAIA",null,null);
        //   https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=6396db33-dc31-4744-b640-21f04c731f9c
//        WeChatUtil.sendMessage("https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=6396db33-dc31-4744-b640-21f04c731f9c",textMessage);
        /*List<String> warehouseHeaderValues= Arrays.asList("原始单号","出库单号","订单编号","物流单号","创建时间","发货时间","揽收时间");
        CreateDocResponse 测试多维表 = WeChatUtil.createDocument(10, "测试多维表", null, null);
        String docid=测试多维表.getDocid();
        String docid="dcTHU_zx3pLcCMYW9ejpDmxwUuVabDhS_NfC6V7_RCjL4Rkv_MJsDq0aR_HX3FpT0mQccWjlSIAEZfeVusFstvng";
        String sheetName="测试文件";
        String sheetId="";
        SmartSheetQueryResponse smartSheetQueryResponse = WeChatUtil.querySmartSheetSheet(docid, null);
        List<SmartSheetQueryResponse.SheetInfo> sheetItem = smartSheetQueryResponse.getSheetList().stream().filter(sl -> ObjectUtil.equal(sheetName, sl.getTitle())).collect(Collectors.toList());
        if(sheetItem.isEmpty()){
            AddSmartSheetResponse addSmartSheetResponse = WeChatUtil.addSmartSheetSheet(docid, sheetName, 0);
            sheetId = addSmartSheetResponse.getProperties().getSheetId();
            for(SmartSheetQueryResponse.SheetInfo si:smartSheetQueryResponse.getSheetList()){
                if(!ObjectUtil.equal(si.getTitle(),sheetName)){
                    WeChatUtil.deleteSmartSheetSheet(docid,si.getSheetId());
                }
            }

            List<AddSmartSheetFieldsRequest.AddField> addFields = warehouseHeaderValues.stream().map(whv -> new AddSmartSheetFieldsRequest.AddField(whv, WeChatFieldType.FIELD_TYPE_TEXT.getCode())).collect(Collectors.toList());
            AddSmartSheetFieldsResponse addSmartSheetFieldsResponses = WeChatUtil.addSmartSheetFields(docid, sheetId, addFields);
            List<String>addFieldIds=addSmartSheetFieldsResponses.getFields().stream().map(AddSmartSheetFieldsResponse.Field::getFieldId).collect(Collectors.toList());
            FieldQueryResponse smartSheetFields=WeChatUtil.getSmartSheetFields(docid,sheetId,null,null, null, 0, 100);
            List<String>fields=smartSheetFields.getFields().stream().map(FieldQueryResponse.Field::getFieldId).filter(fieldId->!addFieldIds.contains(fieldId)).collect(Collectors.toList());
            DeleteSmartSheetFieldsResponse deleteSmartSheetFieldsResponse=WeChatUtil.deleteSmartSheetFields(docid,sheetId,fields);
        }else {
            sheetId=sheetItem.get(0).getSheetId();
        }
        System.out.println(smartSheetQueryResponse);*/
//
//        CreateDocResponse 龙港中通物流跟踪 = WeChatUtil.createDocument(10, "快递拦截统计表", null, null);
//        System.out.println(龙港中通物流跟踪);
      /*  String docid="dcTHU_zx3pLcCMYW9ejpDmxwUuVabDhS_NfC6V7_RCjL4Rkv_MJsDq0aR_HX3FpT0mQccWjlSIAEZfeVusFstvng";
        List<List<String>>values=new ArrayList<>();
        AddSmartSheetResponse addSmartSheetResponse = WeChatUtil.addSmartSheetSheet(docid, "sheetName", 0);
        SmartSheetQueryResponse smartSheetQueryResponse = WeChatUtil.querySmartSheetSheet(docid, null);
        List<SmartSheetQueryResponse.SheetInfo> sheetItem = smartSheetQueryResponse.getSheetList().stream().filter(sl -> ObjectUtil.equal("测试文件", sl.getTitle())).collect(Collectors.toList());
        List<String> warehouseHeaderValues= Arrays.asList("原始单号","出库单号","订单编号","物流单号","创建时间","发货时间","揽收时间");
        String sheetId = sheetItem.get(0).getSheetId();
        values.add(Arrays.asList("1","2","3","4","5","6","7"));
        values.add(Arrays.asList("1","2","3","4","5","6","7"));
        values.add(Arrays.asList("1","2","3","4","5","6","7"));
        values.add(Arrays.asList("1","2","3","4","5","6","7"));
        values.add(Arrays.asList("1","2","3","4","5","6","7"));
        values.add(Arrays.asList("1","2","3","4","5","6","7"));
        values.add(Arrays.asList("1","2","3","4","5","6","7"));



        // 2. 构建记录列表
        List<AddSmartSheetRecordsRequest.Record> records = new ArrayList<>();
        for(List<String> value:values){
            Map<String, List<AddSmartSheetRecordsRequest.Record.CellValue>> recordCellValue = new HashMap<>();
            for (int i=0;i<warehouseHeaderValues.size();i++){
                recordCellValue.put(warehouseHeaderValues.get(i),Collections.singletonList(AddSmartSheetRecordsRequest.Record.CellValue.createText(value.get(i))));
             }
            records.add(new AddSmartSheetRecordsRequest.Record(recordCellValue));
        }



        // 3. 调用API添加记录
        AddSmartSheetRecordsResponse response = WeChatUtil.addSmartSheetRecords(docid, sheetId, null, records);
        System.out.println(response.toString());
*/

//          WeChatUtil.addSmartSheetRecordsBatch();


// docid=dcqIfpIpuoccbzlYuC4ANFUvbUdsX2g-_NIxif-U60QywbLCIjv0tQYTiGhLGKHgt7zUkjB74-UeUx72W9X1pHrg)
      /*  AddSheetResponse 测试文档 = WeChatUtil.addSmartSheet("dcqIfpIpuoccbzlYuC4ANFUvbUdsX2g-_NIxif-U60QywbLCIjv0tQYTiGhLGKHgt7zUkjB74-UeUx72W9X1pHrg", "测试文档", 1);
        System.out.println(测试文档);*/
//{"errcode":0,"errmsg":"ok","properties":{"sheet_id":"EDdY8h","title":"测试文档","index":1}}
//        FieldQueryResponse eDdY8h = WeChatUtil.getSmartSheetFields("dcqIfpIpuoccbzlYuC4ANFUvbUdsX2g-_NIxif-U60QywbLCIjv0tQYTiGhLGKHgt7zUkjB74-UeUx72W9X1pHrg", "EDdY8h");
//        List<AddSmartSheetFieldsRequest.AddField> fieldsToAdd=new ArrayList<>();
//        AddSmartSheetFieldsRequest.AddField addField1 = new AddSmartSheetFieldsRequest.AddField();
//        addField1.setField_title("姓名");
//        addField1.setField_type(WeChatFieldType.FIELD_TYPE_TEXT.getCode());
//        AddSmartSheetFieldsRequest.AddField addField2 = new AddSmartSheetFieldsRequest.AddField();
//        AddSmartSheetFieldsRequest.createTextField("年龄7");
//        addField2.setField_title("年龄7");
//        addField2.setField_type(WeChatFieldType.FIELD_TYPE_NUMBER.getCode());
//        AddSmartSheetFieldsRequest.AddField addField3 = new AddSmartSheetFieldsRequest.AddField();
//        addField3.setField_title("电话");
//        addField3.setField_type(WeChatFieldType.FIELD_TYPE_TEXT.getCode());
//        AddSmartSheetFieldsRequest.AddField addField4 = new AddSmartSheetFieldsRequest.AddField();
//        addField4.setField_title("生日");
//        addField4.setField_type(WeChatFieldType.FIELD_TYPE_TEXT.getCode());
//        AddSmartSheetFieldsRequest.AddField addField5 = new AddSmartSheetFieldsRequest.AddField();
//        addField5.setField_title("位置");
//        addField5.setField_type(WeChatFieldType.FIELD_TYPE_TEXT.getCode());
//        fieldsToAdd.add(addField1);
//        fieldsToAdd.add(addField2);
//        fieldsToAdd.add(addField3);
//        fieldsToAdd.add(addField4);
//        fieldsToAdd.add(addField5);
//        AddSmartSheetFieldsResponse eDdY8h1 = WeChatUtil.addSmartSheetFields("dcqIfpIpuoccbzlYuC4ANFUvbUdsX2g-_NIxif-U60QywbLCIjv0tQYTiGhLGKHgt7zUkjB74-UeUx72W9X1pHrg", "EDdY8h", fieldsToAdd);
//        System.out.println(eDdY8h1);
//        CreateDocResponse rResponse = WeChatUtil.createDocument(10, "销售数据表", null, null);
//        System.out.println(rResponse.getDocid());
//        String docId = rResponse.getDocid();
//        String docId = "dc4Unf5fs8kfKdDTSudFvIci1lVv0v6j9ROqHeZR-2Gg90WDF5GAKIrsTLt-3XOqn6u6HRHyCZTGsPyXuPzO-wnQ";
//        SmartSheetQueryResponse smartSheetQueryResponse = WeChatUtil.querySheets(docId, null);
//        System.out.println(smartSheetQueryResponse);


     /*   AiSheetListResponse aiSheets = DDUtil.getAiSheets("6LeBq413JAeGXx0mFnmgdBXeJDOnGvpb");
        System.out.println(aiSheets);
        // Prepare records to add
        List<AddAiSheetRecordsRequest.Record>records = new ArrayList<>();
        AddAiSheetRecordsRequest.Record record = new AddAiSheetRecordsRequest.Record();

        // Prepare fields - adjust according to your sheet columns
        Map<String, Object> fields = new HashMap<>();
        fields.put("姓名", "安东尼");
        fields.put("年龄", "41");
        fields.put("电话", "1313");
        fields.put("生日", "1984-06-18");
        fields.put("性别", "男");

        record.setFields(fields);
        records.add(record);
        records.add(record);
        records.add(record);
        records.add(record);
        records.add(record);
        records.add(record);
        records.add(record);
        records.add(record);*/


//        Map<String, Object> fields2 = new HashMap<>();
//        fields2.put("姓名", "完成API对接");
//        fields2.put("年龄", "7");
//        AddAiSheetRecordsResponse pfk4c5WG3y = DDUtil.updateDocumentSending2("6LeBq413JAeGXx0mFnmgdBXeJDOnGvpb", "ffpTPaF", records);
 /*       String msgTemplate="多维表测试";
        String warehouseMsgTemplate="姓名：%s\n年龄：%s\n电话：%s\n生日：%s\n性别：%s";
        String endingContent="多维表测试";
        String workbookId="6LeBq413JAeGXx0mFnmgdBXeJDOnGvpb";
        String secret="SEC487fd22f2fa15f69cdbeff10037ff928027918724098bfd86b99d8016be32d7b";
        String token="9b0ac3ca436c87bad260c8510b93e6c0a6ba3ffe3ad1b9ebab159ba710dc2df9";
        List<CreateAiSheetFieldRequest>headerValues=new ArrayList<>();

        headerValues.add(new CreateAiSheetFieldRequest("姓名",FieldType.TEXT.getCode()));
        headerValues.add(new CreateAiSheetFieldRequest("年龄",FieldType.NUMBER.getCode()));
        headerValues.add(new CreateAiSheetFieldRequest("电话",FieldType.TEXT.getCode()));
        headerValues.add(new CreateAiSheetFieldRequest("生日",FieldType.DATE.getCode()));
        headerValues.add(new CreateAiSheetFieldRequest("性别",FieldType.TEXT.getCode()));
        DDUtil.updateAiExcelSendMsg(workbookId,secret,token,null,null,records,"2027-07-08",headerValues,msgTemplate,warehouseMsgTemplate,endingContent,200);
*/


//        DDUtil.getAiSheetRecord()
          /*      // 3. 构建请求
        CreateSheetRequest request = new CreateSheetRequest();
        request.setName("员工信息表3");

        // 添加字段配置
        CreateSheetRequest.FieldConfig nameField = new CreateSheetRequest.FieldConfig();
        nameField.setName("姓名");
        nameField.setType(FieldType.TEXT.getCode());

        CreateSheetRequest.FieldConfig ageField = new CreateSheetRequest.FieldConfig();
        ageField.setName("年龄");
        ageField.setType(FieldType.NUMBER.getCode());
        request.setFields(Arrays.asList(nameField, ageField));
        CreateSheetResponse gjvAqS7AR1DyZMvX = DDUtil.createAiSheet("6LeBq413JAeGXx0mFnmgdBXeJDOnGvpb", request);
         System.out.println(gjvAqS7AR1DyZMvX);
         */
//        SheetListResponse aiSheets = DDUtil.getAiSheets("6LeBq413JAeGXx0mFnmgdBXeJDOnGvpb");
//        System.out.println(aiSheets);

     /*   String baseId = "6LeBq413JAeGXx0mFnmgdBXeJDOnGvpb"; // Your AI table ID
        String sheetIdOrName = "员工信息表3"; // Sheet ID or name

        // Prepare records to add
        AddRecordsRequest.Record[] records = new AddRecordsRequest.Record[1];
        AddRecordsRequest.Record record = new AddRecordsRequest.Record();

        // Prepare fields - adjust according to your sheet columns
        Map<String, Object> fields = new HashMap<>();
        fields.put("姓名", "完成API对接");
        fields.put("年龄", "1");


        record.setFields(fields);
        records[0] = record;

        try {
            AddRecordsResponse response = DDUtil.addAiSheetRecords(baseId, sheetIdOrName,records);

            for (AddRecordsResponse.CreatedRecord created : response.getValue()) {
                System.out.println("Created record ID: " + created.getId());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }*/

        /*DDUtil.deleteAiSheet("6LeBq413JAeGXx0mFnmgdBXeJDOnGvpb","员工信息表");*/
//            CreateDocRequest request = new CreateDocRequest();
//            request.setName("MIND");
//            request.setDocType("MIND"); // 文档类型：DOC(文字)、WORKBOOK(表格)、MIND(脑图)、FOLDER(文件夹)
//        CreateDocResponse gjvAqS7AR1DyZMvX = DDUtil.createDocument("gjvAqS7AR1DyZMvX", request);
//        System.out.println(gjvAqS7AR1DyZMvX);

//            // 3. 调用API获取第一页数据
//            WorkspaceListResponse response = DDUtil.getWorkspaceList(
//                    null, // 首次调用不传nextToken
//                    null,   // 每页大小
//                    null, // 按查看时间倒序
//                    null  // 包含权限信息
//            );
//
//            // 4. 处理响应
//            System.out.println("获取到 " + response.getWorkspaces().size() + " 个知识库");
//            response.getWorkspaces().forEach(workspace -> {
//                System.out.println("知识库名称: " + workspace.getName());
//                System.out.println("知识库ID: " + workspace.getWorkspaceId());
//                System.out.println("访问URL: " + workspace.getUrl());
//                System.out.println("权限角色: " + workspace.getPermissionRole());
//                System.out.println("----------------------");
//            });


//        List<List<String>> remainderData = claimsInfoService.findRemainderData();
//        System.out.println(remainderData);
//        scheduledTasks.scheduledImportClaims();
//        ExpressDeliveryResult result = ExpressDeliveryUtil.queryLogistics(waybillNo);
//        inventoryShortageTasks.scheduledImportClaims();
//       DDUtil.deleteSheet("ZX6GRezwJlyDpZnPI5PXgNoz8dqbropQ","2025-04-17 09:03:27");
//        inventoryShortageTasks.scheduledImportClaims();
//        System.out.println(object);
//        inventoryShortageTasks.scheduledImportClaims();
//        pddTasks.storageScheduledTasks();
//        DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
//        LocalDateTime endTime = LocalDateTime.now();
//        String endSearchTime = endTime.format(FORMATTER);
//        String startSearchTime = endTime.minusDays(30).format(FORMATTER);
//        List<StockSearch2Response.Detail>allStockDetail=new ArrayList<>();
//        StockSearch2Response stockSearch2Response = WDTUtil.stockSpecSearch2(startSearchTime, endSearchTime, 1, 0);
//        List<StockSearch2Response.Detail> details = stockSearch2Response.getDetailList();
//        Integer total = stockSearch2Response.getTotal();
//        int pageSize=2000;
//        allStockDetail.addAll(details);
//        if (total>0){
//            int totalCount=total-pageSize;//剩余订单数量
//            int totalPages=(totalCount+pageSize-1) / pageSize;
//            int currentPageSize=0;
//            for(int pageNo=1;pageNo<=totalPages;pageNo++){
//                currentPageSize=totalCount-pageSize*(pageNo-1);
//                if(currentPageSize>pageSize){
//                    currentPageSize=pageSize;
//                }
//                stockSearch2Response = WDTUtil.stockSpecSearch2(startSearchTime, endSearchTime, currentPageSize, pageNo);
//                allStockDetail.addAll(stockSearch2Response.getDetailList());
//            }
//        }



/*//        DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

//        Integer total = stockSearch2Response.getTotal();
//        Integer pageSize=200;
//        int totalCount=total-pageSize;//剩余订单数量
//        allStockDetail.addAll(details);
//        if (totalCount>0){
//
//            int totalPages=(totalCount+pageSize-1) / pageSize;
//            int currentPageSize=0;
//            for(int pageNo=1;pageNo<=totalPages;pageNo++){
//                currentPageSize=totalCount-pageSize*(pageNo-1);
//                if(currentPageSize>pageSize){
//                    currentPageSize=pageSize;
//                }
//                tradeQueryResponse = WDTUtil.queryOrderList(startTimeStr, endTimeStr,  findStatus, currentPageSize, pageNo);
////                assert tradeQueryResponse != null;
////                orders.addAll(tradeQueryResponse.getOrders());
//            }
//        }

//        List<Long>ids=selfOrderService.list(new QueryWrapper<SelfOrderDO>().in("src_tids", Arrays.asList(1))).stream().map(SelfOrderDO::getId).collect(Collectors.toList());

//        pddTasks.storageScheduledTasks();
//        ExpressDeliveryController expressDeliveryController = new ExpressDeliveryController();
//        expressDeliveryController.logisticsMonitoring(ExpressDeliveryUtil.queryLogistics("78520202602619"));

//        ExpressDeliveryResult result = ExpressDeliveryUtil.queryLogistics("78921244083001");
//        System.out.println(result);
//        ExpressDeliveryResult result2 = ExpressDeliveryUtil.queryLogistics("78507584135047");
//        System.out.println(result2);
//        redisService.setWithExpire("333","",-1, TimeUnit.SECONDS);
//        scheduledTasks.scheduledImportClaims();
//        AsyncService.setCollectionDelayStatic(new SelfOrderDO(),0);
//        Set<String> keys = WAREHOUSE_INTERCEPT_CONFIG.keySet();
//        for (String key:keys){
//            WarehouseConfigEntity warehouseConfigEntity = WAREHOUSE_INTERCEPT_CONFIG.get(key);
//            WarehouseInterceptionConfig libraryInterceptionConfig = warehouseConfigEntity.getLibraryInterceptionConfig();
//            DDUtil.deleteSheet(libraryInterceptionConfig.getWorkbookId(),"2025-07");
//            List<WarehouseExpressDeliveryConfig> collect = warehouseConfigEntity.getTransitInterceptionConfigs().stream().filter(e -> ObjectUtil.equal(e.getPlatform(), 1)).collect(Collectors.toList());
//            for (WarehouseExpressDeliveryConfig warehouseExpressDeliveryConfig:collect){
//            DDUtil.deleteSheet(warehouseExpressDeliveryConfig.getWorkbookId(),"2025-07");
//            }
//
//        }


//        pddTasks.scheduledTasks();
//        redisService.setWithExpire("123123213","222",7, TimeUnit.SECONDS);
//        DDUtil.getToken();
//        selfOrderCollectTasks.disposeScheduledTasks();
//        scheduledTasks.scheduledImportClaims();
//        QueryWrapper<SelfOrderDO> queryWrapper = new QueryWrapper<>();
//        queryWrapper.like("logistics_name","韵达");
//        List<SelfOrderDO> list = selfOrderService.list(queryWrapper);
//        for (SelfOrderDO  so:list){
//            ExpressDeliveryResult result = ExpressDeliveryUtil.queryLogistics(so.getLogisticsNo());
//        }

//        selfOrderCollectTasks.storageScheduledTasks();
//        orderLogisticsAbnormalityCollectTasks.disposeScheduledTasks();
//        selfOrderCollectTasks.disposeScheduledTasks();
//     List<SelfOrderDO> selfOrders = selfOrderService.findSelfOrders("2025-6-23 00:00:00", "2025-6-23 10:00:00", "1");
//     System.out.println(selfOrders);
//        List<List<String>> remainderData = claimsInfoService.findRemainderData();
//        pDDSendGoodsTasks.scheduledTasks();
//        pddTasks.scheduledTasks();
//        scheduledTasks.scheduledImportClaims();
//        JSONObject customerGroupList = weChatUtil.getCustomerGroupList(1000);
//        System.out.println(customerGroupList);
//        pddTasks.scheduledTasks();
        //    String S ="SEC487fd22f2fa15f69cdbeff10037ff928027918724098bfd86b99d8016be32d7b";
//    String S ="9b0ac3ca436c87bad260c8510b93e6c0a6ba3ffe3ad1b9ebab159ba710dc2df9";
//        List<ClaimsInfoDO> list = claimsInfoService.list();
//        String collect = list.stream().map(i -> "原始单号:" + i.getWaybillNo() + "出库单号: " + i.getShopName() + ";物流公司:" + i.getRemarks() + ";物流单号:" + i.getCreateTime() + "拦截类型").collect(Collectors.joining("\n"));
//        DDUtil.sendMessageWebhook("SEC487fd22f2fa15f69cdbeff10037ff928027918724098bfd86b99d8016be32d7b","9b0ac3ca436c87bad260c8510b93e6c0a6ba3ffe3ad1b9ebab159ba710dc2df9",collect);
//        DDUtil.robotSend("SEC487fd22f2fa15f69cdbeff10037ff928027918724098bfd86b99d8016be32d7b","测试","https://oapi.dingtalk.com/robot/send?access_token=9b0ac3ca436c87bad260c8510b93e6c0a6ba3ffe3ad1b9ebab159ba710dc2df9");
//        pddTasks.scheduledTasks();
//        DDUtil.updateRange("Obva6QBXJw6lYwAMFlr3arwxVn4qY5Pr","Sheet1","A96:A96", Arrays.asList(Arrays.asList("213123")));
//        List<List<String>> dlpLastStartIndex = scheduledTasks.getDLPLastStartIndex();
//        System.out.println(dlpLastStartIndex);
//        Integer lpLastStartIndex = scheduledTasks.optimizeTable("sys:lpRangeAddress:lastIndexKey");
        //scheduledTasks.supplementalDividingLines(680,"Obva6QBXJw6lYwAMFlr3arwxVn4qY5Pr","Sheet1", Arrays.asList("年月日","",""),"213123");
//        scheduledTasks.scheduledImportClaims();
//        System.out.println(1);
//        JSONObject sheets = DDUtil.getSheets("ZX6GRezwJlyDpZnPIna9eB5q8dqbropQ");
//        System.out.println(sheets);
//        scheduledTasks.test();
//        System.out.println(lpLastStartIndex);
//        String s = redisService.get("sys:lpRangeAddress:lastIndexKey");
//        System.out.println(s);
//        String workbookId="Obva6QBXJw6lYwAMFlr3arwxVn4qY5Pr";
//        JSONObject wbResult = DDUtil.getSheets(workbookId);
//        System.out.println(wbResult);
//        String workbookId="Obva6QBXJw6lYwAMFlr3arwxVn4qY5Pr";
        *//*    JSONObject wbResult = DDUtil.getSheets(workbookId);
            JSONArray value = wbResult.getJSONArray("value");
            List<String> ids = value.stream().filter(val -> {
            JSONObject nval = (JSONObject) val;String name = nval.getString("name");
            return name.equals("Sheet1");}).map(val->{JSONObject nval = (JSONObject) val;
            return nval.getString("id");
            }).collect(Collectors.toList());
            String sheetId="";
            if(!ids.isEmpty()){
                sheetId=ids.get(0);
            }*//*
//        String sheetId="s1";
//        DDUtil.deleteRows(workbookId,sheetId,50,1);
//        LambdaQueryWrapper<ClaimsInfoDO> eq = new LambdaQueryWrapper<>(ClaimsInfoDO.class)
//                .eq(ClaimsInfoDO::getId, "userId")
//                .eq(ClaimsInfoDO::getText, "activityId");
//        List<ClaimsInfoDO> list = claimsInfoService.list(eq);
//        List<List<String>> remainderData = claimsInfoService.findRemainderData();
//        System.out.println(remainderData);*/
//        return result;
    }

//    @GetMapping("/getTest")
//    public void getTest(HttpServletResponse response,JSONObject object) {
//        System.out.println(object);
//    }



    @GetMapping("/uploadAiExcel")
    @Async
    public void uploadAiExcel(@RequestParam(value = "uploadPath", required = false) String uploadPath) {
        // 文件夹获取
        File pdfDirectory = new File(uploadPath);
        if (!pdfDirectory.exists()) {
            log.error("上传目录不存在:{}", uploadPath);
            return;
        }
        File[] files = pdfDirectory.listFiles();
        if (files == null) {
            log.error("上传目录为空:{}", uploadPath);
            return;
        }
        AddAiSheetRecordsRequest.Record[] recordArr = new AddAiSheetRecordsRequest.Record[files.length];
        int index = 0;
        // 遍历上传文件
        for (File file : files) {
            String fileName = file.getName();
            String filePreName = fileName.substring(0, fileName.lastIndexOf("."));
            if (file.isDirectory()) {
                log.info("跳过文件夹:{}", fileName);
                continue;
            }
            long size = file.length();
            String mimeType;
            if (fileName.endsWith(".pdf")) {
                mimeType = "application/pdf";
            } else if (fileName.endsWith(".xlsx")) {
                mimeType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
            } else if (fileName.endsWith(".xls")) {
                mimeType = "application/vnd.ms-excel";
            } else if (fileName.endsWith(".jpg") || fileName.endsWith(".jpeg")) {
                mimeType = "image/jpeg";
            } else {
                log.info("跳过未知文件:{}", fileName);
                continue;
            }
            // 获取上传资源
            JSONObject jsonObject = DDUtil.queryUploadInfo(size, mimeType, fileName);
            if (jsonObject == null) {
                log.info("跳过上传资源获取失败:{}", fileName);
                continue;
            }
            String uploadUrl = jsonObject.getString("uploadUrl");
            String resourceId = jsonObject.getString("resourceId");
            String resourceUrl = jsonObject.getString("resourceUrl");
            // 上传文件
            DDUtil.uploadFilesToUrl(uploadUrl, file);
            // 附件组装
            AddAiSheetRecordAttachmentDTO[] attachments = new AddAiSheetRecordAttachmentDTO[1];
            AddAiSheetRecordAttachmentDTO attachment = new AddAiSheetRecordAttachmentDTO(fileName, size, mimeType, resourceUrl, resourceId);
            attachments[0] = attachment;
            // 数据组装
            AddAiSheetRecordsRequest.Record record = new AddAiSheetRecordsRequest.Record();
            Map<String,Object> fields = new HashMap<>();
            fields.put("标题", filePreName);
            fields.put("附件", attachments);
            record.setFields(fields);
            recordArr[index++] = record;
        }
        // 新增数据
        AddAiSheetRecordsResponse addAiSheetRecordsResponse = DDUtil.addAiSheetRecords(null, "测试", recordArr);
        log.info("新增AI表格记录返回:{}", JSON.toJSONString(addAiSheetRecordsResponse));
    }


}
